package com.bkhech.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.bkhech.mapper.CommentMapper;
import com.bkhech.mapper.UsersMapper;
import com.bkhech.pojo.Comment;
import com.bkhech.pojo.Users;
import com.bkhech.pojo.bo.CommentBO;
import com.bkhech.pojo.convertor.CommentConvertor;
import com.bkhech.pojo.dto.CommentDTO;
import com.bkhech.pojo.vo.CommentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collection;

/**
 * CommentService
 *
 * @author guowm
 * @date 2024-11-06
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CommentService {

    private final CommentMapper commentMapper;

    private final UsersMapper usersMapper;

    public CommentVO createComment(CommentBO commentBO) {

        Comment comment = CommentConvertor.INSTANCE.commentBO2Entity(commentBO);
        comment.setCreatedTime(LocalDateTime.now());
        commentMapper.insert(comment);

        CommentVO commentVO = CommentConvertor.INSTANCE.commentEntity2VO(comment);
        this.buildCommentUserInfo(commentBO.getCommentUserId(), commentVO);
        commentVO.setCommentId(comment.getId());
        return commentVO;
    }


    /**
     * 根据朋友圈
     *
     * @param friendCircleIds 朋友圈id集合
     * @return
     */
    public Collection<CommentVO> queryAll(Collection<String> friendCircleIds) {
        CommentDTO commentDTO = new CommentDTO();
        commentDTO.setFriendCircleIdList(friendCircleIds);
        return commentMapper.selectListByFriendCircleId(commentDTO);
    }


    private void buildCommentUserInfo(String commentUserId, CommentVO commentVO) {
        Users commentUser = usersMapper.selectById(commentUserId);
        commentVO.setCommentUserNickname(commentUser.getNickname());
        commentVO.setCommentUserFace(commentUser.getFace());
    }

    public void deleteComment(String commentUserId, String commentId, String friendCircleId) {
        QueryWrapper<Comment> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.lambda().eq(Comment::getCommentUserId, commentUserId)
                .eq(Comment::getId, commentId)
                .eq(Comment::getFriendCircleId, friendCircleId);
        commentMapper.delete(deleteWrapper);
    }
}
